package cn.com.cfae.iras.doc.analyze.components.integrity;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.*;

@Component("I1021")
@Scope("prototype")
public class I1021 extends BaseComponent {
    private static Logger log = LoggerFactory.getLogger(I1021.class);

    @Autowired
    private HandingData handingData;
    @Override
    public List<ComponentResult> handlerM() {
        log.info("获取I1021组件M");
        List<ComponentResult> componentResults = checkRulesI1021("M-5",getCatalogId(),"M-5",getRuleTitle(),"(M6)");
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        log.info("获取I1021组件BM");
        List<ComponentResult> componentResults = checkRulesI1021("BM-5","BM-5","BM-5",getRuleTitle(),"(M6)");
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        log.info("获取I1021组件DM");
        List<ComponentResult> componentResults = checkRulesI1021("DM-5","DM-5","DM-5",getRuleTitle(),"(D6)");
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        log.info("获取I1021组件BDM");
        List<ComponentResult> componentResults = checkRulesI1021("BDM-5","BDM-5","BDM-5",getRuleTitle(),"(D6)");
        return componentResults;
    }

    private List<ComponentResult> checkRulesI1021(String model,String catalogId,String chapterId,String ruleName,String subTitle){

        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;
        List<ComponentResult.TextPosition> contentAndPositionList = null;
        int startPage = 0;
        int pageNum = 0;
        boolean flag = false;
        Map<String,String> keywords = getKeywords();
        boolean isAllErr = false;
        int headPage = 0;
        try {

            if (extractData!=null){
                ChapterModel chapterModel = extractData.getChapterModel(model);
                startPage = chapterModel!=null? chapterModel.getStartPage():0;
                pageNum = startPage;
                headPage = startPage;
                boolean isEqual = false;
                if (chapterModel!=null){
                    ExtractBizModel ywgxm = chapterModel.getModel("YWGXM");
                    List<ExtractItem> extractItemList = chapterId!=null?ywgxm.getExtractItemList():null;

                    if (!isEmptyOfValue(extractItemList)){
                        isEqual = true;
                        TextLayout ywgxmHead = ywgxm.getTableNameTextLayout();
                        if (ywgxmHead!=null&&StringUtils.isNotEmpty(ywgxmHead.getText())){
                            headPage =ywgxmHead.getPageNumber();
                            headPage = headPage!=0?headPage:startPage;
                            contentAndPositionList = new ArrayList<>();
                            ComponentResult.TextPosition contentAndPosition = new ComponentResult().new TextPosition();
                            contentAndPosition.setX(ywgxmHead.getLeft());
                            contentAndPosition.setY(ywgxmHead.getTop());
                            contentAndPosition.setContent(ywgxmHead.getText());
                            contentAndPositionList.add(contentAndPosition);
                        }
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"是否以列表形式披露已完工项目","正确",false,getRegulationId(),headPage,contentAndPositionList,"01");
                        componentResults.add(componentResult);
                    }else {
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"是否以列表形式披露已完工项目","疑似披露已完工项目情况,建议人工核对",true,getRegulationId(),startPage,null,"03");
                        componentResults.add(componentResult);
                        for (String key : keywords.keySet()){
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-"+keywords.get(key),"未触发检查",true,getRegulationId(),startPage,contentAndPositionList,"03");
                            componentResults.add(componentResult);
                        }
                    }
                    if (isEqual){
                        KVText xmztKvTextKey = getKVTextKey(model, "YWGXM", "XMZT");
                        if (xmztKvTextKey!=null){
                            List<TextLayout> textLayoutList = xmztKvTextKey.getTextLayoutList();
                            pageNum = CollectionUtils.isNotEmpty(textLayoutList)?textLayoutList.get(0).getPageNumber():startPage;
                            pageNum = pageNum!=0?pageNum:startPage;
                            contentAndPositionList = getContentAndPositionList(xmztKvTextKey);
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-项目主体","正确",false,getRegulationId(),pageNum,contentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            isAllErr = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-项目主体","缺失",true,getRegulationId(),headPage,null,"02");
                            componentResults.add(componentResult);
                        }

                        KVText xmmcKvTextKey = getKVTextKey(model, "YWGXM", "XMMC");
                        if (xmmcKvTextKey!=null){
                            List<TextLayout> textLayoutList = xmmcKvTextKey.getTextLayoutList();
                            pageNum = CollectionUtils.isNotEmpty(textLayoutList)?textLayoutList.get(0).getPageNumber():startPage;
                            pageNum = pageNum!=0?pageNum:startPage;
                            contentAndPositionList = getContentAndPositionList(xmmcKvTextKey);
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-项目名称","正确",false,getRegulationId(),pageNum,contentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            isAllErr = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-项目名称","缺失",true,getRegulationId(),headPage,null,"02");
                            componentResults.add(componentResult);
                        }

                        KVText xmlbKvTextKey = getKVTextKey(model, "YWGXM", "XMLB");
                        if (xmlbKvTextKey!=null){
                            List<TextLayout> textLayoutList = xmlbKvTextKey.getTextLayoutList();
                            pageNum = CollectionUtils.isNotEmpty(textLayoutList)?textLayoutList.get(0).getPageNumber():startPage;
                            pageNum = pageNum!=0?pageNum:startPage;
                            contentAndPositionList = getContentAndPositionList(xmlbKvTextKey);
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-项目类别","正确",false,getRegulationId(),pageNum,contentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            isAllErr = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-项目类别","缺失",true,getRegulationId(),headPage,null,"02");
                            componentResults.add(componentResult);
                        }

                        KVText xmszdKvTextKey = getKVTextKey(model, "YWGXM", "XMSZD");
                        if (xmszdKvTextKey!=null){
                            List<TextLayout> textLayoutList = xmszdKvTextKey.getTextLayoutList();
                            pageNum = CollectionUtils.isNotEmpty(textLayoutList)?textLayoutList.get(0).getPageNumber():startPage;
                            pageNum = pageNum!=0?pageNum:startPage;
                            contentAndPositionList = getContentAndPositionList(xmszdKvTextKey);
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-项目所在地","正确",false,getRegulationId(),pageNum,contentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            isAllErr = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-项目所在地","缺失",true,getRegulationId(),headPage,null,"02");
                            componentResults.add(componentResult);
                        }

                        KVText yxszeKvTextKey = getKVTextKey(model, "YWGXM", "YXSZE");
                        if (yxszeKvTextKey!=null){
                            List<TextLayout> textLayoutList = yxszeKvTextKey.getTextLayoutList();
                            pageNum = CollectionUtils.isNotEmpty(textLayoutList)?textLayoutList.get(0).getPageNumber():startPage;
                            pageNum = pageNum!=0?pageNum:startPage;
                            contentAndPositionList = getContentAndPositionList(yxszeKvTextKey);
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-已销售总额","正确",false,getRegulationId(),pageNum,contentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            isAllErr = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-已销售总额","缺失",true,getRegulationId(),headPage,null,"02");
                            componentResults.add(componentResult);
                        }

                        KVText xsjdKvTextKey = getKVTextKey(model, "YWGXM", "XSJD");
                        if (xsjdKvTextKey!=null){
                            List<TextLayout> textLayoutList = xsjdKvTextKey.getTextLayoutList();
                            pageNum = CollectionUtils.isNotEmpty(textLayoutList)?textLayoutList.get(0).getPageNumber():startPage;
                            pageNum = pageNum!=0?pageNum:startPage;
                            contentAndPositionList = getContentAndPositionList(xsjdKvTextKey);
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-销售进度","正确",false,getRegulationId(),pageNum,contentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            isAllErr = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-销售进度","缺失",true,getRegulationId(),headPage,null,"02");
                            componentResults.add(componentResult);
                        }

                        KVText hkqkKvTextKey = getKVTextKey(model, "YWGXM", "HKQK");
                        if (hkqkKvTextKey!=null){
                            List<TextLayout> textLayoutList = hkqkKvTextKey.getTextLayoutList();
                            pageNum = CollectionUtils.isNotEmpty(textLayoutList)?textLayoutList.get(0).getPageNumber():startPage;
                            pageNum = pageNum!=0?pageNum:startPage;
                            contentAndPositionList = getContentAndPositionList(hkqkKvTextKey);
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-回款情况","正确",false,getRegulationId(),pageNum,contentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            isAllErr = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-回款情况","缺失",true,getRegulationId(),headPage,null,"02");
                            componentResults.add(componentResult);
                        }

                        KVText xmpwKvTextKey = getKVTextKey(model, "YWGXM", "XMPW");
                        if (xmpwKvTextKey!=null){
                            List<TextLayout> textLayoutList = xmpwKvTextKey.getTextLayoutList();
                            pageNum = CollectionUtils.isNotEmpty(textLayoutList)?textLayoutList.get(0).getPageNumber():startPage;
                            pageNum = pageNum!=0?pageNum:startPage;
                            contentAndPositionList = getContentAndPositionList(xmpwKvTextKey);
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-项目批文情况","正确",false,getRegulationId(),pageNum,contentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            isAllErr = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-项目批文情况","缺失",true,getRegulationId(),headPage,null,"02");
                            componentResults.add(componentResult);
                        }
                    }



                    /*if (CollectionUtils.isNotEmpty(ywgxm)){
                        flag = true;
                        boolean isEqual = false;
                        String entryKey = null;
                        for (Map<String,ExtractItem> map : ywgxm){
                            for (Map.Entry<String, ExtractItem> entry : map.entrySet()) {
                                entryKey = entry.getKey();
                                if (StringUtils.isNotEmpty(entryKey)){
                                    ExtractItem extm =  entry.getValue();

                                    if (extm!=null){
                                        isEqual = true;
                                        KVText value = extm.getValue();
                                        pageNum = value!=null?value.getPageNumber():startPage;
                                        pageNum = pageNum!=0?pageNum:startPage;
                                        contentAndPositionList = value!=null?getContentAndPositionList(value):null;
                                    }
                                    break;
                                }
                            }
                            if (isEqual)
                                break;
                        }
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"是否以列表形式披露已完工项目","正确",false,getRegulationId(),pageNum,contentAndPositionList,"01");
                        componentResults.add(componentResult);
                    }else {
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"是否以列表形式披露已完工项目","未披露已完工项目情况,请人工核对",true,getRegulationId(),startPage,contentAndPositionList,"02");
                        componentResults.add(componentResult);
                    }

                    if (flag){
                        String entryKey = null;
                        for (String key : keywords.keySet()){
                            boolean isEqual = false;
                            for (Map<String,ExtractItem> map : ywgxm){
                                for (Map.Entry<String, ExtractItem> entry : map.entrySet()) {
                                    entryKey = entry.getKey();
                                    if (StringUtils.isNotEmpty(entryKey)&&key.equals(entryKey)){
                                        isEqual = true;
                                        ExtractItem extm =  entry.getValue();
                                        if (extm!=null){
                                            KVText value = extm.getValue();
                                            pageNum = value!=null?value.getPageNumber():startPage;
                                            pageNum = pageNum!=0?pageNum:startPage;
                                            contentAndPositionList = value!=null?getContentAndPositionList(value):null;
                                        }
                                        break;
                                    }
                                }
                                if (isEqual)
                                    break;
                            }
                            if (isEqual){
                                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-"+keywords.get(key),"正确",false,getRegulationId(),pageNum,contentAndPositionList,"01");
                                componentResults.add(componentResult);
                            }else {
                                isAllErr = true;
                                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-"+keywords.get(key),"缺失",true,getRegulationId(),pageNum,contentAndPositionList,"02");
                                componentResults.add(componentResult);
                            }
                        }
                    }else {
                        for (String key : keywords.keySet()){
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-"+keywords.get(key),"未触发检查",true,getRegulationId(),startPage,contentAndPositionList,"02");
                            componentResults.add(componentResult);
                        }
                    }*/
                }
            }

            if (isAllErr){
                for (ComponentResult result:componentResults){
                    result.setExist("02");
                }
            }

        }catch (Exception e){
            componentResults.clear();
            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"是否以列表形式披露已完工项目","未识别,建议人工核对",true,getRegulationId(),startPage,contentAndPositionList,"03");
            componentResults.add(componentResult);
            for (String key : keywords.keySet()){
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,subTitle+"关键词检查-"+keywords.get(key),"未触发检查",true,getRegulationId(),startPage,contentAndPositionList,"03");
                componentResults.add(componentResult);
            }
            log.error(e.getMessage(),e);
        }
        return componentResults;
    }

    private Map<String,String> getKeywords(){
        Map<String, String> items = new HashMap<>();
        items.put("XMZT","项目主体");
        items.put("XMMC","项目名称");
        items.put("XMLB","项目类别");
        items.put("XMSZD","项目所在地");
        items.put("YXSZE","已销售总额");
        items.put("XSJD","销售进度");
        items.put("HKQK","回款情况");
        items.put("XMPW","项目批文情况");
        return  items;
    }

    private boolean isEmptyOfValue(List<ExtractItem> extractItemList){
        if (CollectionUtils.isEmpty(extractItemList)){
            return true;
        }

        for (ExtractItem extractItem : extractItemList){
            KVText key = extractItem.getKey();
            if (key!=null){
                return false;
            }
        }

        return true;
    }
}
